using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace Deloitte.Windows.Controls
{
	/// <summary>
	/// Summary description for ctlDataView.
	/// </summary>
	public class DataViewSortControl : System.Windows.Forms.UserControl
	{
        private DataGridViewComboBoxColumn orderColumn;
		private DataView myDataView;
		private bool isAddingSortRows=false;		
		private DataTable dtAvailSortFields = new DataTable("tblSortFields");
        private DataTable dtSelectedSortFields = new DataTable("tblSelectedSortFields");
		internal System.Windows.Forms.Button btnMove;
		internal System.Windows.Forms.Button btnMoveBack;
		internal System.Windows.Forms.Button btnUp;
		internal System.Windows.Forms.Button btnDown;
		private System.Windows.Forms.GroupBox gbSortFields;        
        private System.Windows.Forms.GroupBox gbAvailableFields;
        private DataGridView availableFieldsGrid;
        private Button sortButton;
        private DataGridView selectedFieldsGrid;
		/// <summary> 
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;
		
		public DataViewSortControl(DataView dv)
		{
			// This call is required by the Windows.Forms Form Designer.
			InitializeComponent();

			this.CreateSortDataTableColumns();            
			this.MyDataView = dv;
            this.availableFieldsGrid.DataSource = this.dtAvailSortFields;
            this.selectedFieldsGrid.DataSource = this.dtSelectedSortFields;
            this.orderColumn =  new DataGridViewComboBoxColumn();
            // 
            // orderColumn
            // 
            this.orderColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells;
            this.orderColumn.HeaderText = "Order";
            this.orderColumn.Name = "orderColumn";
            this.orderColumn.Resizable = System.Windows.Forms.DataGridViewTriState.True;
            this.orderColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
            this.orderColumn.Width = 64;
            this.orderColumn.Items.AddRange(new object[]{"ASC", "DESC"});
            
            this.selectedFieldsGrid.Columns.Add(this.orderColumn);
		
			//this.cbSortField.SelectedValueChanged += new EventHandler(cboSortField_SelectedValueChanged);
		}
		private void CreateSortDataTableColumns()
		{
			this.dtAvailSortFields.Columns.Add("Selected", typeof(bool));
			this.dtAvailSortFields.Columns.Add("Column", typeof(string));
			this.dtAvailSortFields.Constraints.Add("PK", this.dtAvailSortFields.Columns["Column"], true);
			this.dtSelectedSortFields.Columns.Add("Selected", typeof(bool));
			this.dtSelectedSortFields.Columns.Add("Column", typeof(string));
			//this.dtSelectedSortFields.Columns.Add("Order", typeof(string));
			this.dtSelectedSortFields.Constraints.Add("PK", this.dtSelectedSortFields.Columns["Column"], true);
			this.dtSelectedSortFields.RowChanged +=new DataRowChangeEventHandler(dtSelectedSortFields_RowChanged);
		}
		/// <summary> 
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}
		private void SetMyDataView(DataView dv)
		{
			try
			{
				//this.cbSortField.Items.Clear();				
				DataRow dr;
				this.dtAvailSortFields.Clear();
				this.dtSelectedSortFields.Clear();			
				foreach(DataColumn dc in dv.Table.Columns)
				{
					dr = this.dtAvailSortFields.NewRow();
					dr[0] = false;
					dr[1] = dc.ColumnName;
					this.dtAvailSortFields.Rows.Add(dr);
				}
				this.myDataView = dv;
                
				//set the datagrid table styles
				//Hannon.Common.Utility.AutoFormatDataGridTableStyle(this.dtAvailSortFields, this.dgAvailableSortFields, false, false);
				//this.dgAvailableSortFields.TableStyles[0].GridColumnStyles["Column"].ReadOnly = true;				
				//if (tsSelectedField==null)this.SetSelectedFieldTableStyle();		
				//Hannon.Common.Utility.AutoFormatDataGridTableStyle(this.dtSelectedSortFields, this.dgSortFields, false, false);
				//this.dgSortFields.TableStyles[0].GridColumnStyles["Column"].ReadOnly = true;			
			}
			catch(Exception ex){throw new Exception(ex.ToString());}
		}
		
		public DataView MyDataView
		{
			get{return this.myDataView;}
			set{this.SetMyDataView(value);}
		}
		#region Component Designer generated code
		/// <summary> 
		/// Required method for Designer support - do not modify 
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DataViewSortControl));
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
            this.btnMove = new System.Windows.Forms.Button();
            this.btnMoveBack = new System.Windows.Forms.Button();
            this.btnUp = new System.Windows.Forms.Button();
            this.btnDown = new System.Windows.Forms.Button();
            this.gbSortFields = new System.Windows.Forms.GroupBox();
            this.selectedFieldsGrid = new System.Windows.Forms.DataGridView();
            this.gbAvailableFields = new System.Windows.Forms.GroupBox();
            this.availableFieldsGrid = new System.Windows.Forms.DataGridView();
            this.sortButton = new System.Windows.Forms.Button();
            this.gbSortFields.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.selectedFieldsGrid)).BeginInit();
            this.gbAvailableFields.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.availableFieldsGrid)).BeginInit();
            this.SuspendLayout();
            // 
            // btnMove
            // 
            this.btnMove.BackColor = System.Drawing.Color.Navy;
            this.btnMove.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnMove.Font = new System.Drawing.Font("Tahoma", 8.898876F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnMove.Image = ((System.Drawing.Image)(resources.GetObject("btnMove.Image")));
            this.btnMove.Location = new System.Drawing.Point(309, 48);
            this.btnMove.Name = "btnMove";
            this.btnMove.Size = new System.Drawing.Size(23, 24);
            this.btnMove.TabIndex = 11;
            this.btnMove.UseVisualStyleBackColor = false;
            this.btnMove.Click += new System.EventHandler(this.btnMove_Click);
            // 
            // btnMoveBack
            // 
            this.btnMoveBack.BackColor = System.Drawing.Color.Navy;
            this.btnMoveBack.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnMoveBack.Font = new System.Drawing.Font("Tahoma", 8.898876F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnMoveBack.Image = ((System.Drawing.Image)(resources.GetObject("btnMoveBack.Image")));
            this.btnMoveBack.Location = new System.Drawing.Point(309, 72);
            this.btnMoveBack.Name = "btnMoveBack";
            this.btnMoveBack.Size = new System.Drawing.Size(23, 24);
            this.btnMoveBack.TabIndex = 12;
            this.btnMoveBack.UseVisualStyleBackColor = false;
            this.btnMoveBack.Click += new System.EventHandler(this.btnMoveBack_Click);
            // 
            // btnUp
            // 
            this.btnUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.btnUp.BackColor = System.Drawing.Color.Navy;
            this.btnUp.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnUp.Font = new System.Drawing.Font("Tahoma", 8.898876F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnUp.Image = ((System.Drawing.Image)(resources.GetObject("btnUp.Image")));
            this.btnUp.Location = new System.Drawing.Point(211, 55);
            this.btnUp.Name = "btnUp";
            this.btnUp.Size = new System.Drawing.Size(24, 24);
            this.btnUp.TabIndex = 13;
            this.btnUp.UseVisualStyleBackColor = false;
            this.btnUp.Click += new System.EventHandler(this.btnUp_Click);
            // 
            // btnDown
            // 
            this.btnDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.btnDown.BackColor = System.Drawing.Color.Navy;
            this.btnDown.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnDown.Font = new System.Drawing.Font("Tahoma", 8.898876F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnDown.Image = ((System.Drawing.Image)(resources.GetObject("btnDown.Image")));
            this.btnDown.Location = new System.Drawing.Point(211, 80);
            this.btnDown.Name = "btnDown";
            this.btnDown.Size = new System.Drawing.Size(24, 24);
            this.btnDown.TabIndex = 14;
            this.btnDown.UseVisualStyleBackColor = false;
            this.btnDown.Click += new System.EventHandler(this.btnDown_Click);
            // 
            // gbSortFields
            // 
            this.gbSortFields.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.gbSortFields.Controls.Add(this.selectedFieldsGrid);
            this.gbSortFields.Controls.Add(this.btnDown);
            this.gbSortFields.Controls.Add(this.btnUp);
            this.gbSortFields.Font = new System.Drawing.Font("Tahoma", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.gbSortFields.Location = new System.Drawing.Point(336, 0);
            this.gbSortFields.Name = "gbSortFields";
            this.gbSortFields.Size = new System.Drawing.Size(240, 135);
            this.gbSortFields.TabIndex = 17;
            this.gbSortFields.TabStop = false;
            this.gbSortFields.Text = "Selected Fields";
            // 
            // selectedFieldsGrid
            // 
            this.selectedFieldsGrid.AllowUserToAddRows = false;
            this.selectedFieldsGrid.AllowUserToDeleteRows = false;
            dataGridViewCellStyle1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.selectedFieldsGrid.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
            this.selectedFieldsGrid.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.selectedFieldsGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.selectedFieldsGrid.Location = new System.Drawing.Point(2, 16);
            this.selectedFieldsGrid.Name = "selectedFieldsGrid";
            this.selectedFieldsGrid.Size = new System.Drawing.Size(203, 116);
            this.selectedFieldsGrid.TabIndex = 15;
            // 
            // gbAvailableFields
            // 
            this.gbAvailableFields.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)));
            this.gbAvailableFields.Controls.Add(this.availableFieldsGrid);
            this.gbAvailableFields.Font = new System.Drawing.Font("Tahoma", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.gbAvailableFields.Location = new System.Drawing.Point(8, -1);
            this.gbAvailableFields.Name = "gbAvailableFields";
            this.gbAvailableFields.Size = new System.Drawing.Size(300, 136);
            this.gbAvailableFields.TabIndex = 17;
            this.gbAvailableFields.TabStop = false;
            this.gbAvailableFields.Text = "Available Fields";
            // 
            // availableFieldsGrid
            // 
            this.availableFieldsGrid.AllowUserToAddRows = false;
            this.availableFieldsGrid.AllowUserToDeleteRows = false;
            dataGridViewCellStyle2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.availableFieldsGrid.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle2;
            this.availableFieldsGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.availableFieldsGrid.Dock = System.Windows.Forms.DockStyle.Fill;
            this.availableFieldsGrid.Location = new System.Drawing.Point(3, 14);
            this.availableFieldsGrid.Name = "availableFieldsGrid";
            this.availableFieldsGrid.Size = new System.Drawing.Size(294, 119);
            this.availableFieldsGrid.TabIndex = 11;
            // 
            // sortButton
            // 
            this.sortButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.sortButton.AutoSize = true;
            this.sortButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.sortButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.sortButton.Location = new System.Drawing.Point(11, 136);
            this.sortButton.Name = "sortButton";
            this.sortButton.Size = new System.Drawing.Size(34, 24);
            this.sortButton.TabIndex = 31;
            this.sortButton.Text = "&Sort";
            this.sortButton.UseVisualStyleBackColor = true;
            this.sortButton.Click += new System.EventHandler(this.sortButton_Click);
            // 
            // DataViewSortControl
            // 
            this.AutoScroll = true;
            this.Controls.Add(this.sortButton);
            this.Controls.Add(this.gbAvailableFields);
            this.Controls.Add(this.gbSortFields);
            this.Controls.Add(this.btnMove);
            this.Controls.Add(this.btnMoveBack);
            this.Font = new System.Drawing.Font("Microsoft Sans Serif", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Name = "DataViewSortControl";
            this.Size = new System.Drawing.Size(576, 162);
            this.Tag = "";
            this.gbSortFields.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.selectedFieldsGrid)).EndInit();
            this.gbAvailableFields.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.availableFieldsGrid)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion

		private void btnMove_Click(object sender, System.EventArgs e)
		{
			try
			{				
				this.isAddingSortRows=true;
				ArrayList rows = new ArrayList();
				foreach(DataRow dr in this.dtAvailSortFields.Rows)
				{
					if((bool)dr[0]==true)
					{
						rows.Add(dr);						
					}
				}
				for(int i = 0;i < rows.Count;i++)
				{
					this.dtSelectedSortFields.ImportRow((DataRow)rows[i]);
					this.dtAvailSortFields.Rows.Remove((DataRow) rows[i]);					
				}
				this.isAddingSortRows= false;
				this.dtSelectedSortFields_RowChanged(null, null);
			}
			catch(Exception ex){throw new Exception(ex.ToString());}
			finally{this.isAddingSortRows=false;}
		}

		private void btnMoveBack_Click(object sender, System.EventArgs e)
		{
			try
			{				
				ArrayList rows = new ArrayList();
				foreach(DataRow dr in this.dtSelectedSortFields.Rows)
				{
					if((bool)dr[0]==true)
					{
						dr[0] = false;
						rows.Add(dr);						
					}
				}
				for(int i = 0;i < rows.Count;i++)
				{
					this.dtAvailSortFields.ImportRow((DataRow)rows[i]);
					this.dtSelectedSortFields.Rows.Remove((DataRow) rows[i]);
				}
			}
			catch(Exception ex){throw new Exception(ex.ToString());}					
		}

		private void btnUp_Click(object sender, System.EventArgs e)
		{			
			try
			{
				object[] swapItems, currItems;
                string ascDesc = string.Empty;
				DataRow  dr;				
				for(int i=1; i<this.dtSelectedSortFields.Rows.Count; i++)
				{
					dr = this.dtSelectedSortFields.Rows[i];
					if((bool)dr[0]==true)
					{					
						currItems=this.dtSelectedSortFields.Rows[i].ItemArray;
						swapItems = this.dtSelectedSortFields.Rows[i-1].ItemArray;
                        if (this.selectedFieldsGrid["orderColumn", i - 1].Value != null) { ascDesc = this.selectedFieldsGrid["orderColumn", i - 1].Value.ToString(); }
						this.dtSelectedSortFields.Rows[i-1]["Column"] = "TempKey";
						this.dtSelectedSortFields.Rows[i]["Column"] = "TempKey2";
						this.dtSelectedSortFields.Rows[i-1].ItemArray = currItems;
                        this.selectedFieldsGrid["orderColumn", i-1].Value = this.selectedFieldsGrid["orderColumn", i].Value;
						this.dtSelectedSortFields.Rows[i].ItemArray= swapItems;
                        this.selectedFieldsGrid["orderColumn", i].Value = ascDesc;
					}
				}
			}
			catch(Exception ex){throw new Exception(ex.ToString());}
		}


	
		private void dtSelectedSortFields_RowChanged(object sender, DataRowChangeEventArgs e)
		{
			if(!this.isAddingSortRows)
			{				
				//Hannon.Common.Utility.AutoFormatDataGridTableStyle(this.dtSelectedSortFields, this.dgSortFields, false, false);
				//if (this.dtSelectedSortFields.Rows.Count==0)this.dgSortFields.ReadOnly = true;				
			}
		}

		private void btnDown_Click(object sender, System.EventArgs e)
		{
			try
			{
				object[] swapItems, currItems;
                string ascDesc = string.Empty;
				DataRow  dr;				
				for(int i=0; i<this.dtSelectedSortFields.Rows.Count-1; i++)
				{
					dr = this.dtSelectedSortFields.Rows[i];
					if((bool)dr[0]==true)
					{					
						currItems=this.dtSelectedSortFields.Rows[i].ItemArray;
						swapItems = this.dtSelectedSortFields.Rows[i+1].ItemArray;

						this.dtSelectedSortFields.Rows[i+1]["Column"] = "TempKey";
						this.dtSelectedSortFields.Rows[i]["Column"] = "TempKey2";
						this.dtSelectedSortFields.Rows[i+1].ItemArray = currItems;
                        if (this.selectedFieldsGrid["orderColumn", i + 1].Value != null) { ascDesc = this.selectedFieldsGrid["orderColumn", i + 1].Value.ToString(); }
                        this.selectedFieldsGrid["orderColumn", i + 1].Value = this.selectedFieldsGrid["orderColumn", i].Value;
						this.dtSelectedSortFields.Rows[i].ItemArray= swapItems;
                        this.selectedFieldsGrid["orderColumn", i].Value = ascDesc;
						i+=1;
					}
				}
			}
			catch(Exception ex){throw new Exception(ex.ToString());}
		}

	
        private void sortButton_Click(object sender, EventArgs e)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            for (int i = 0; i < this.selectedFieldsGrid.Rows.Count; i++)
            {
                if (i > 0) sb.Append(", ");
                sb.Append(this.selectedFieldsGrid["Column",i].Value.ToString());
                if (this.selectedFieldsGrid["orderColumn", i].Value.ToString() == "DESC") sb.Append(" DESC");
            }
            this.myDataView.Sort = sb.ToString(); 
        }
     
	}
}
